package org.jypj.dev.controller;

import java.util.*;


import com.alibaba.fastjson.JSON;
import org.jypj.dev.constant.JpushConstant;
import org.jypj.dev.dao.IGiveWorkDao;
import org.jypj.dev.dao.IUserDao;
import org.jypj.dev.vo.hxVo.PushObject;
import org.jypj.dev.model.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.jypj.dev.service.ICodeDataService;
import org.jypj.dev.service.IGiveWorkService;
import org.jypj.dev.service.IRoadService;
import org.jypj.dev.service.IUserService;
import org.jypj.dev.util.*;
import org.jypj.dev.vo.*;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * GiveWork控制器
 *
 * @author ChenYu
 */
@Controller
@RequestMapping("giveWorkController")
public class GiveWorkController extends BaseController {

    @Resource
    private IGiveWorkService giveWorkService;

    @Resource
    private IGiveWorkDao giveWorkDao;

    @Resource
    private IRoadService roadService;

    @Resource
    private IUserDao userDao;

    @Resource
    private ICodeDataService codeDataService;

    @Resource
    private IUserService userService;

    /**
     * 跳转至人员派班页面
     * 并设置派班天数
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "toGiveWorkMain.action")
    public String toGiveWorkMain(HttpServletRequest request) {
        List<DateWork> dateWorks = new ArrayList<>();
        String yyyy = DateUtils.getTodayString("yyyy");
        String workDate = DateUtils.getTodayString("MM-dd");
        int giveWorkDay = Integer.parseInt(PropertyUtil.getProperties("give_work_day"));
        for (int i = 0; i < giveWorkDay; i++) {
            DateWork dateWork = new DateWork();
            String workDate1 = DateUtils.getSomeDayString(workDate, "MM-dd", i);
            dateWork.setWorkDate(workDate1);
            int roadNum = giveWorkDao.selectRoadNum(yyyy + "-" + workDate1);
            int userNum = giveWorkDao.selectUserNum(yyyy + "-" + workDate1);
            dateWork.setRoadNum(roadNum);
            dateWork.setUserNum(userNum);
            dateWorks.add(dateWork);
        }
        request.setAttribute("dateWorks", dateWorks);
        return "back/givework/give_work_main";
    }


    /**
     * 跳转到派班历史记录表
     *
     * @return
     */
    @RequestMapping(value = "toGiveWorkList.action")
    public String toGiveWorkList(HttpServletRequest request) {
        String startDate = DateUtils.getTodayString("yyyy-MM-dd");
        request.setAttribute("startDate", startDate);
        return "back/givework/give_work_record_list";
    }

    /**
     * 分页查询
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectOnePage.action")
    public Page selectOnePage(Page page, String searchKey, String workDate) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("searchKey", searchKey);
        queryMap.put("workDate", workDate);
        page = giveWorkService.selectOnePageByMap(page, queryMap);
        return page;
    }


    /**
     * 查询所有数据接口
     *
     * @return code =-1 表示有异常 code=-2 表示没有数据 datas 菜单数据
     */
    @RequestMapping("selectAllGiveWork.action")
    @ResponseBody
    public Map<String, Object> selectAllGiveWork(String roadId, String searchKey, String num, String tempTrain) {
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Road> stringRoadMap = new HashMap<>();
        Map<String, Object> queryRoadMap = new HashMap<>();
        Map<String, Object> queryGiveWorkMap = new HashMap<>();
        int giveWorkDay = Integer.parseInt(PropertyUtil.getProperties("give_work_day"));
        String todayString = DateUtils.getTodayString("yyyy-MM-dd");
        String someDayString = DateUtils.getSomeDayString(todayString, "yyyy-MM-dd", giveWorkDay);
        int code = 0;
        try {
            //查询得到交路的信息
            queryRoadMap.put("searchKey", searchKey);
            queryRoadMap.put("num", num);
            queryRoadMap.put("tempTrain", tempTrain);
            queryRoadMap.put("roadId", roadId);
            queryRoadMap.put("startDate", todayString);
            queryRoadMap.put("endDate", someDayString);
            List<Road> roads = roadService.selectAllByMap(queryRoadMap);
            //将日期信息设置在交路中
            for (Road road : roads) {
                for (int i = 0; i < giveWorkDay; i++) {
                    String dayString = DateUtils.getSomeDayString(todayString, "yyyy-MM-dd", i);
                    road.getDateUserWorks().put(dayString, new ArrayList<>());
                }
                stringRoadMap.put(road.getId(), road);
            }
            //查询出设置的天数内的派班信息
            queryGiveWorkMap.put("startDate", todayString);
            queryGiveWorkMap.put("endDate", someDayString);
            List<GiveWork> giveWorks = giveWorkService.selectAllByMap(queryGiveWorkMap);

            //将查询出来的信息与交路对应
            for (GiveWork giveWork : giveWorks) {
                User user = getGiveWorkUser(giveWork);
                Road road = stringRoadMap.get(giveWork.getRoadId());
                if (null == road) {
                    continue;
                }
                road.getDateUserWorks().get(giveWork.getWorkDate()).add(user);
            }
            dataMap.put("datas", roads);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 查询用户
     *
     * @param dateStr
     * @return
     */
    @RequestMapping(value = "toUserList.action")
    public String toUserList(String giveWorkId, String dateStr, String roadId, HttpServletRequest request) {
        String remindTime = "";
        request.setAttribute("dateStr", dateStr);
        Road road = roadService.selectRoadById(roadId);
        List<Train> trains = road.getTrains();
        remindTime = giveWorkDao.lastRemindTime(roadId);
        if (StringUtil.isEmpty(remindTime) && trains.size() > 0) {
            String startTime = trains.get(0).getStartTime();
            remindTime = DateUtils.getBeforeTime(startTime, getSetting().getHours());
        }
        request.setAttribute("road", road);
        request.setAttribute("giveWorkId", giveWorkId);
        request.setAttribute("remindTime", remindTime);
        return "back/givework/give_work_user_list";
    }


    /**
     * 查询派班用户
     *
     * @param giveWorkId
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllRoadGiveWork.action")
    public Map<String, Object> selectAllRoadGiveWork(String giveWorkId) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            GiveWork giveWork = giveWorkDao.selectGiveWorkById(giveWorkId);
            List<GiveWork> giveWorks = giveWorkDao.selectAllRoadGiveWork(giveWork);
            dataMap.put("giveWorks", giveWorks);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 修改派班信息
     *
     * @return
     */
    @RequestMapping(value = "toUpdateGiveWork.action")
    public String toUpdateGiveWork(String giveWorkId, HttpServletRequest request) {
        GiveWork giveWork = giveWorkDao.selectGiveWorkById(giveWorkId);
        request.setAttribute("giveWork", giveWork);
        return "back/givework/give_work_update";
    }

    /**
     * 派班
     *
     * @param giveWork
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "updateGiveWork.action")
    public Map<String, Object> updateGiveWork(GiveWork giveWork) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            GiveWork giveWork1 = giveWorkDao.selectGiveWorkById(giveWork.getId());
            giveWork1.setTrainNum(giveWork.getTrainNum());
            giveWork1.setRemindTime(giveWork.getRemindTime());
            giveWorkDao.updateGiveWork(giveWork1);
            User giveWorkUser = getGiveWorkUser(giveWork1);
            dataMap.put("giveWorkUser", giveWorkUser);
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }

    /**
     * 查询用户列表
     *
     * @param dateStr
     * @return
     */
    @RequestMapping(value = "selectOnePageUser.action")
    @ResponseBody
    public Page selectUserList(Page page, String dateStr, String roadId, String searchCode) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("dateStr", dateStr);
        queryMap.put("searchCode", searchCode);
        queryMap.put("roadId", roadId);
        List<User> users = userDao.selectOnePageByMap2(page, queryMap);
        page.setResult(users);
        return page;
    }

    /**
     * 添加用户
     *
     * @param dateStr
     * @param roadId
     * @param users
     * @return
     */
    @RequestMapping(value = "addUsersInRoad.action")
    @ResponseBody
    public Map<String, Object> addUserInRoad(String giveWorkId, String dateStr, String roadId, String users, String remindTime, String gsm1, String gsm2) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        Road road = roadService.selectRoadById(roadId);
        List<UserTrainNumVo> utn = JSON.parseArray(users, UserTrainNumVo.class);
        List<GiveWork> giveWorks = new ArrayList<>();
        for (UserTrainNumVo u : utn) {
            GiveWork giveWork = new GiveWork();
            giveWork.setId(StringUtil.getLowUUID());
            giveWork.setUserId(u.getUserId());
            giveWork.setWorkDate(dateStr);
            giveWork.setTrainNum(u.getTrainNum());
            giveWork.setRemindTime(StringUtil.isEmpty(remindTime) ? "00:00" : remindTime);
            giveWork.setRoadId(roadId);
            giveWork.setHadResp("0");
            giveWork.setHadRemind(0);
            giveWorks.add(giveWork);
        }
        road.setGsm1(gsm1);
        road.setGsm2(gsm2);
        roadService.updateRoad(road);
        for (GiveWork s : giveWorks) {//判断如果叫班时间小于当前时间 就可以进行推送
            String rTime = s.getWorkDate() + " " + s.getRemindTime();
            String currentTime = DateUtils.getTodayString("yyyy-MM-dd HH:mm");
            User user = userService.selectUserById(s.getUserId());
            PushObject pushObject = new PushObject();
            if (rTime.compareTo(currentTime) <= 0) {
                pushObject.setPushType(JpushConstant.REMIND_WORK);
                pushObject.setPushTitle("工作提醒");
                pushObject.setPushContent(s.getWorkDate() + "有新的工作。");
                pushObject.setPushValue(s);
                System.out.println("推送人：" + user.getUserNum());
                HxUtil.sendMsgToOneUser(user.getUserNum(), pushObject);
                s.setIsRemind(1);
            } else {
                pushObject.setPushType(JpushConstant.GIVE_WORK);
                pushObject.setPushTitle("派班提醒");
                pushObject.setPushContent(s.getWorkDate() + "有新的工作。");
                pushObject.setPushValue(s);
                System.out.println("推送人：" + user.getUserNum());
                HxUtil.sendMsgToOneUser(user.getUserNum(), pushObject);
            }
        }
        try {
            giveWorkService.saveGiveWorks(giveWorks, giveWorkId);
        } catch (Exception e) {
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }


    /**
     * 查询所有用户
     *
     * @param q
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllUser.action")
    public List<User> selectAll(String q) {
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("q", q);
        List<User> users = userDao.selectAllByMap(queryMap);
        return users;
    }

    /**
     * 核对车组号是否存在
     *
     * @param trainNum
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "checkTrainNum.action")
    public String checkTrainNum(String trainNum) {
        String czhwh = codeDataService.selectItemTextByItemValue("czhwh", trainNum);
        return StringUtil.isEmpty(czhwh) ? "" : czhwh;
    }

    /**
     * 查询所有用户
     *
     * @param q
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "selectAllRoadUser.action")
    public List<RoadUserVo> selectAllRoadUser(String q) {
        String todayString = DateUtils.getTodayString("yyyy-MM-dd");
        String someDayString = DateUtils.getSomeDayString(todayString, "yyyy-MM-dd", 3);
        Map<String, Object> queryMap = new HashMap<>();
        queryMap.put("q", q);
        queryMap.put("startDate", todayString);
        queryMap.put("endDate", someDayString);
        List<RoadUserVo> roadUserVos = giveWorkDao.selectAllRoadUserByMap(queryMap);
        for (RoadUserVo roadUserVo : roadUserVos) {
            roadUserVo.setUserStr(StringUtil.isEmpty(roadUserVo.getUserStr()) ? "" : roadUserVo.getUserStr().replace(",", "<br/>"));
            roadUserVo.setTrainNumStr(StringUtil.isEmpty(roadUserVo.getTrainNumStr()) ? "" : roadUserVo.getTrainNumStr().replace(",", "<br/>"));
        }
        return roadUserVos;
    }

    /**
     * 根据ID删除
     *
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "deleteById.action")
    public Map<String, Object> deleteById(String id) {
        Map<String, Object> dataMap = new HashMap<>();
        int code = 0;
        try {
            GiveWork giveWork = giveWorkService.selectGiveWorkById(id);
            giveWorkService.deleteGiveWorkById(id);
            if (giveWork != null) {
                PushObject pushObject = new PushObject();
                pushObject.setPushType(JpushConstant.DELETE_WORK);
                pushObject.setPushValue(giveWork);
                System.out.println("删除派班" + giveWork);
                HxUtil.sendMsgToOneUser(giveWork.getUserNum(), pushObject);
            }
        } catch (Exception e) {
            e.printStackTrace();
            code = -1;
        }
        dataMap.put("code", code);
        return dataMap;
    }


    /**
     * 根据派班得到用户
     *
     * @param giveWork
     * @return
     */
    public User getGiveWorkUser(GiveWork giveWork) {
        User user = new User();
        user.setId(giveWork.getUserId());
        user.setUserNum(giveWork.getUserNum());
        user.setUsername(giveWork.getUserName());
        user.setGiveWorkId(giveWork.getId());
        user.setGiveWorkRemindTime(giveWork.getRemindTime());
        user.setTrainNum(giveWork.getTrainNum());
        user.setHadRemind(giveWork.getHadRemind());
        return user;
    }
}